package com.toidep.fragment.others;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnCompletionListener;
import io.vov.vitamio.MediaPlayer.OnPreparedListener;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.VideoView;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.adapters.CommentAdapter;
import com.toidep.adapters.VideoSuggestionAdapter;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.bitmaputil.AsyncTask;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.entities.TagEntity;
import com.toidep.entities.VideoEntity;
import com.toidep.interfaces.DialogListener;
import com.toidep.interfaces.ResponseListener;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DatetimeUtil;
import com.toidep.utilities.DialogUtility;
import com.toidep.videoplayer.util.StringUtils;
import com.toidep.widgets.sectionlist.AmazingListView;

public class VideoPlayerFragment extends BaseFragment implements OnCompletionListener, OnClickListener{

	private MainActivity mainActivity;
	
	private String videoId;
	
	private View view;
	private String mPath;
	private String mTitle;
	private VideoView mVideoView;
	private View mVolumeBrightnessLayout;
	private ImageView mOperationBg;
	private ImageView mOperationPercent;
	private AudioManager mAudioManager;
	private int mMaxVolume;
	private int mVolume = -1;
	private float mBrightness = -1f;
	private int mLayout = VideoView.VIDEO_LAYOUT_ZOOM;
	private GestureDetector mGestureDetector;
	protected boolean isLandScape = false;
	private int mVideoMode = VideoView.VIDEO_LAYOUT_SCALE;
	private RelativeLayout layoutPlayer;
	
	private RelativeLayout layoutController;
	private static final int sDefaultTimeout = 6000;
	private static final int FADE_OUT = 1;
	private static final int SHOW_PROGRESS = 2;
	private long mDuration;
	private boolean isShowing;
	private boolean mDragging;
	private ProgressBar mProgress;
	private boolean mInstantSeeking = true;
	private TextView mEndTime, mCurrentTime;
	private TextView mFileName;
	private AudioManager mAM;
	private ImageButton mPauseButton;
	private ImageButton btnFullMode;
	
	private static final int TAB_INTRODUCTION = 1;
	private static final int TAB_SUGGESTION = 2;
	private static final int TAB_COMMENTS = 3;
	private VideoEntity currentVideoItem;
	private RelativeLayout buttonIntroduction, buttonSuggestion, buttonComments;
	private RelativeLayout layoutIntroduction, layoutSuggestion, layoutComments;
	private ImageView imvModelImage;
	private TextView txvModelName;
	private TextView textVideoTitle, textVideoCreated, textTotalView, textIntroduction;
	private LinearLayout layoutTags;
	
	private AmazingListView listVideosSuggestion, listVideoComments;
	private VideoSuggestionAdapter adapterVideosSuggestion;
	private CommentAdapter adapterVideoComments;

	private TextView buttonComment;
	
	
	public static VideoPlayerFragment newInstance(String videoId) {
		VideoPlayerFragment myFragment = new VideoPlayerFragment();
	    
		myFragment.videoId = videoId;
	    
	    return myFragment;
	}
	
	public void setVideoId(String id) {
		this.videoId = id;
	}
	
	public void setBaseValues() {
		mainActivity = (MainActivity) getActivity();
		mainActivity.currentCategory = Constants.CATEGORY_VIDEO_DETAIL;
		mainActivity.mainFragment.setTittle(mainActivity.getString(R.string.label_category_video_detail));
		mainActivity.mainFragment.showButtonSlide(false);

		mainActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
//		if (!LibsChecker.checkVitamioLibs(getActivity()))
//			return null;
		view = inflater.inflate(R.layout.videoview, container, false);
		
		initComponents();
		
		setBaseValues();
		
		getVideoDetail();
		
//		startPlayVideo();

		return view;
	}
	
	public void clearVideoData() {
		try {
			if (mVideoView.isPlaying())
				mVideoView.stopPlayback();
			currentVideoItem = null;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	private void initComponents() {
		
//		try {
//			mPath = getArguments().getString("file");
//			mTitle = getArguments().getString("name");
//		} catch (Exception e) {
////			mPath = Environment.getExternalStorageDirectory() + "//Music//Video//ForeverAndOne.mp4";
//		}
		
//		if (mPath == null)
//			mPath = Environment.getExternalStorageDirectory() + "//Music//Video//ForeverAndOne.mp4";
//			mPath = Environment.getExternalStorageDirectory() + "//Samsung//Video//Wonders_of_Nature.mp4";
		
//		mTitle = "test video";
		
		layoutPlayer = (RelativeLayout) view.findViewById(R.id.layoutVideoPlayer);
		layoutPlayer.getLayoutParams().width = ConfigUtility.scrWidth;
	    layoutPlayer.getLayoutParams().height = (int) (ConfigUtility.scrWidth * 0.8);
		
		mVideoView = (VideoView) view.findViewById(R.id.surface_view);
		mVolumeBrightnessLayout = view.findViewById(R.id.operation_volume_brightness);
		mOperationBg = (ImageView) view.findViewById(R.id.operation_bg);
		mOperationPercent = (ImageView) view.findViewById(R.id.operation_percent);
		mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
		mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		
		mGestureDetector = new GestureDetector(this.getActivity(), new MyGestureListener());
		
		// Layouts
		buttonIntroduction = (RelativeLayout) view.findViewById(R.id.layoutButtonVideoIntroduction);
		buttonIntroduction.setOnClickListener(this);
		buttonSuggestion = (RelativeLayout) view.findViewById(R.id.layoutButtonVideoSuggestion);
		buttonSuggestion.setOnClickListener(this);
		buttonComments = (RelativeLayout) view.findViewById(R.id.layoutButtonVideoComment);
		buttonComments.setOnClickListener(this);
		edtComment = (EditText) view.findViewById(R.id.edtComment);
		buttonComment = (TextView) view.findViewById(R.id.buttonComment);
		buttonComment.setOnClickListener(this);
		
		layoutIntroduction = (RelativeLayout) view.findViewById(R.id.layoutVideoDetailIntroduction);
		layoutSuggestion = (RelativeLayout) view.findViewById(R.id.layoutVideoDetailSuggestion);
		layoutComments = (RelativeLayout) view.findViewById(R.id.layoutVideoDetailComments);
		
		view.findViewById(R.id.layoutButtons).setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		
		imvModelImage = (ImageView) view.findViewById(R.id.imgModelThumb);
		txvModelName = (TextView) view.findViewById(R.id.txvModelName);
		
		// Khoi tao list Video lien quan
		listVideosSuggestion = (AmazingListView) view.findViewById(R.id.listVideoSuggestion);
		listVideosSuggestion.setAdapter(adapterVideosSuggestion = new VideoSuggestionAdapter(this, -1, videoId));
		listVideosSuggestion.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
		adapterVideosSuggestion.setAmazingListView(listVideosSuggestion, ConfigUtility.PAGE_SIZE);
		adapterVideosSuggestion.notifyMayHaveMorePages();
		listVideosSuggestion.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				adapterVideosSuggestion.onItemClick(arg2);
			}
		});
		
		// Khoi tao list Comments cua VIdeo
		listVideoComments = (AmazingListView) view.findViewById(R.id.listVideoComments);
		listVideoComments.setAdapter(adapterVideoComments = new CommentAdapter(this, Constants.CATEGORY_VIDEO_DETAIL, Constants.COMMENT_TYPE_VIDEO, videoId));
		listVideoComments.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
		adapterVideoComments.setAmazingListView(listVideoComments, ConfigUtility.PAGE_SIZE);
		adapterVideoComments.notifyMayHaveMorePages();
		
		// Khoi tao cac thanh phan o tab Gioi Thieu
		textVideoTitle = (TextView) view.findViewById(R.id.txvVideoTitle);
		textVideoCreated = (TextView) view.findViewById(R.id.txvVideoUpdateTime);
		textTotalView = (TextView) view.findViewById(R.id.txvTotalViews);
		layoutTags = (LinearLayout) view.findViewById(R.id.layoutTags);
		textIntroduction = (TextView) view.findViewById(R.id.txvIntroduction);
		
		// MEdia COntroller
		mAM = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
		layoutController = (RelativeLayout) view.findViewById(R.id.layoutMediaController);
		isShowing = true;
		btnFullMode = (ImageButton) view.findViewById(R.id.mediacontroller_fullscreen);
		btnFullMode.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				changeFullScreen();
			}
		});
		mPauseButton = (ImageButton) view.findViewById(R.id.mediacontroller_play_pause);
		if (mPauseButton != null) {
			mPauseButton.requestFocus();
			mPauseButton.setOnClickListener(mPauseListener);
		}
		mProgress = (ProgressBar) view.findViewById(R.id.mediacontroller_seekbar);
		if (mProgress != null) {
			if (mProgress instanceof SeekBar) {
				SeekBar seeker = (SeekBar) mProgress;
				seeker.setOnSeekBarChangeListener(mSeekListener);
				seeker.setThumbOffset(1);
			}
			mProgress.setMax(1000);
		}
		mEndTime = (TextView) view.findViewById(R.id.mediacontroller_time_total);
		mCurrentTime = (TextView) view.findViewById(R.id.mediacontroller_time_current);
		mFileName = (TextView) view.findViewById(R.id.mediacontroller_file_name);
		mHandleController.sendEmptyMessageDelayed(FADE_OUT, sDefaultTimeout);
		
		
		// Bug #220 - Start
		edtComment.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					if (!mainActivity.checkUserLogon()) {
						return true;
					}
				}
				return false;
			}
		});
		// Bug #220 - End
		// Bug #314 - Start
		/*edtComment.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
					postComment();

					return true;
				}
				return false;
			}
		});*/
		edtComment.setImeOptions(EditorInfo.IME_ACTION_DONE);
		edtComment.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					postComment();
				return true;
			}
		});
		// Bug #314 - End
	}
	
	public void getVideoDetail() {
		
		showProgressDialog();
		
		ApiController.getVideoDetail(
				getActivity(), 
				videoId, 
				new ResponseListener() {
					
					@Override
					public void processResponse(int inintstall) {
						Log.e(getTag(), "getVideoDetail error");
						closeProgressDialog();
					}
					
					@Override
					public void processResponse(String response) {
						Log.e(getTag(), "getVideoDetail SUCCESS------------------");
						closeProgressDialog();
						if (response != null) {
							currentVideoItem = ParseJSON.getVideoDetailObjectFromResponse(response);
							if (currentVideoItem == null)
								Log.e(getTag(), "getVideoDetail currentVideoItem null");
							else {
								setVideoInformation();
								checkVitamioLibs();
							}
						}
						
					}
				});
		
	}
	
	private void setVideoInformation() {
		
		if (adapterVideosSuggestion != null) {
			adapterVideosSuggestion.clear();
			adapterVideosSuggestion.notifyMayHaveMorePages();
		}
		
		if (adapterVideoComments != null) {
			adapterVideoComments.clear();
			adapterVideoComments.notifyMayHaveMorePages();
		}
		
		switchMenuVideo(TAB_INTRODUCTION);
		
		txvModelName.setText(currentVideoItem.getModelName());
		
		if (currentVideoItem.getModelIcon() == null || currentVideoItem.getModelIcon() == "") {
			imvModelImage.setVisibility(View.GONE);
		} else {
			imvModelImage.setVisibility(View.VISIBLE);
			
			int icon_size = ConfigUtility.size_icon;
			LinearLayout.LayoutParams param1 = new LinearLayout.LayoutParams(icon_size, icon_size);
			imvModelImage.setLayoutParams(param1);
			imvModelImage.setScaleType(ScaleType.FIT_XY);
			if (mainActivity != null) {
				mainActivity.loadImage(imvModelImage,
						currentVideoItem.getModelIcon(), icon_size, icon_size,
						icon_size, icon_size);
			}
		}
		
		mTitle = currentVideoItem.getTitle();
		mPath = currentVideoItem.getUrl();
		
		textVideoTitle.setText(mTitle);
		textVideoCreated.setText(String.format(mainActivity.getResources()
				.getString(R.string.text_created_at), DatetimeUtil
				.convertTimestampToString(currentVideoItem.getCreated())));
		String totalView = currentVideoItem.getTotalView() + " views";
		textTotalView.setText(totalView);
		
		textIntroduction.setText(currentVideoItem.getCaption());
		
		// list tags
		ArrayList<TagEntity> listTags = currentVideoItem.getTags();
		if (listTags != null) {
			for (int i = 0; i < listTags.size(); i++) {
				String tag = listTags.get(i).getName();
				TextView textView = new TextView(getActivity());
				textView.setPadding(5, 5, 5, 5);
				textView.setOnClickListener(new TagOnClickListener(tag));
				if (i != listTags.size()-1) 
					tag += ",";
				textView.setText(tag);
				layoutTags.addView(textView);
			}
		}
		
		if (adapterVideosSuggestion != null) {
			adapterVideosSuggestion.setParentId(currentVideoItem.getId());
		}
		
		if (adapterVideoComments != null) {
			adapterVideoComments.setParentId(currentVideoItem.getId());
		}
		
	}
	public void startPlayVideo() {
		
		mFileName.setText(mTitle);
		
		Log.e(getTag(), "mPath = " + mPath);
		
		if (!mPath.startsWith("http:")) {
			mVideoView.setVideoURI(Uri.parse(mPath));
		}

		else {
			Log.i("VideoPlayerActivity Oplayer", "2: " + mPath);
			mVideoView.setVideoPath(mPath);
			Log.i("VideoPlayerActivity Oplayer", "3");
//			mVideoView.setMediaController(new MediaController(getActivity()));
			mVideoView.requestFocus();
			mVideoView.setOnPreparedListener(new OnPreparedListener() {
				public void onPrepared(MediaPlayer mp) {
					mp.setPlaybackSpeed(1.0f);
				}
			});
			
//			mVideoView.setOnSubtitleUpdateListener(new OnSubtitleUpdateListener() {
//				public void onSubtitleUpdate(String arg0) {
//
//				}
//
//				public void onSubtitleUpdate(byte[] arg0, int arg1,
//						int arg2) {
//				}
//			});
			
		}
		mVideoView.setOnCompletionListener(this);
		
		mVideoView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return onTouchThis(event);
			}
		});
		
		mHandleTime.removeCallbacks(mRunnable);
		mHandleTime.postDelayed(mRunnable, 1000);

	}
	
	private void endGesture() {
		mVolume = -1;
		mBrightness = -1f;

		mDismissHandler.removeMessages(0);
		mDismissHandler.sendEmptyMessageDelayed(0, 500);
	}
	
	private class MyGestureListener extends SimpleOnGestureListener {

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			if (mLayout == VideoView.VIDEO_LAYOUT_ZOOM)
				mLayout = VideoView.VIDEO_LAYOUT_ORIGIN;
			else
				mLayout++;
			if (mVideoView != null)
				mVideoView.setVideoLayout(mLayout, 0);
			return true;
		}
		
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			float mOldX = e1.getX(), mOldY = e1.getY();
			int y = (int) e2.getRawY();
			Display disp = VideoPlayerFragment.this.getActivity().getWindowManager().getDefaultDisplay();
			int windowWidth = disp.getWidth();
			int windowHeight = disp.getHeight();

			if (mOldX > windowWidth * 4.0 / 5)
				onVolumeSlide((mOldY - y) / windowHeight);
			else if (mOldX < windowWidth / 5.0)
				onBrightnessSlide((mOldY - y) / windowHeight);

			return super.onScroll(e1, e2, distanceX, distanceY);
		}
	}
	
	private void onVolumeSlide(float percent) {
		if (mVolume == -1) {
			mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			if (mVolume < 0)
				mVolume = 0;

			mOperationBg.setImageResource(R.drawable.video_volumn_bg);
			mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
		}

		int index = (int) (percent * mMaxVolume) + mVolume;
		if (index > mMaxVolume)
			index = mMaxVolume;
		else if (index < 0)
			index = 0;

		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

		ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
		lp.width = view.findViewById(R.id.operation_full).getLayoutParams().width
				* index / mMaxVolume;
		mOperationPercent.setLayoutParams(lp);
	}

	private void onBrightnessSlide(float percent) {
		if (mBrightness < 0) {
			mBrightness = getActivity().getWindow().getAttributes().screenBrightness;
			if (mBrightness <= 0.00f)
				mBrightness = 0.50f;
			if (mBrightness < 0.01f)
				mBrightness = 0.01f;

			mOperationBg.setImageResource(R.drawable.video_brightness_bg);
			mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
		}
		WindowManager.LayoutParams lpa = getActivity().getWindow().getAttributes();
		lpa.screenBrightness = mBrightness + percent;
		if (lpa.screenBrightness > 1.0f)
			lpa.screenBrightness = 1.0f;
		else if (lpa.screenBrightness < 0.01f)
			lpa.screenBrightness = 0.01f;
		getActivity().getWindow().setAttributes(lpa);

		ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
		lp.width = (int) (view.findViewById(R.id.operation_full).getLayoutParams().width * lpa.screenBrightness);
		mOperationPercent.setLayoutParams(lp);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		if (mVideoView != null)
			mVideoView.pause();
		mHandleController.removeMessages(FADE_OUT);
		mHandleTime.removeCallbacks(mRunnable);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (mVideoView != null)
			mVideoView.resume();
		mHandleController.sendEmptyMessageDelayed(FADE_OUT, sDefaultTimeout);
		mHandleTime.removeCallbacks(mRunnable);
		mHandleTime.postDelayed(mRunnable, 1000);
		
		boolean loginStatus = SharePreference.getInstance(mainActivity)
				.getLoginStatus();
		if (loginStatus) {
			edtComment.setText("");
			
		} else {
			edtComment.setText("Đề nghị login để bình luận");
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mVideoView != null)
			mVideoView.stopPlayback();
	}
	
	private Handler mDismissHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mVolumeBrightnessLayout.setVisibility(View.GONE);
		}
	};

	private EditText edtComment;
	
	public void onConfigurationChanged(android.content.res.Configuration newConfig) {

		int orientation = newConfig.orientation;
		if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
			isLandScape = true;
			mVideoMode = VideoView.VIDEO_LAYOUT_STRETCH;
			WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
		    attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
		    getActivity().getWindow().setAttributes(attrs);
		    ((MainActivity) getActivity()).mainFragment.showHeader(false);
		    mVideoView.getLayoutParams().width = ConfigUtility.scrHeight;
		    mVideoView.getLayoutParams().height = ConfigUtility.scrWidth;
		    layoutPlayer.getLayoutParams().width = ConfigUtility.scrHeight;
		    layoutPlayer.getLayoutParams().height = ConfigUtility.scrWidth;
		} else {
			isLandScape = false;
			mVideoMode = VideoView.VIDEO_LAYOUT_SCALE;
			WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
		    attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
		    getActivity().getWindow().setAttributes(attrs);
		    ((MainActivity) getActivity()).mainFragment.showHeader(true);
		    mVideoView.getLayoutParams().width = ConfigUtility.scrWidth;
		    mVideoView.getLayoutParams().height = (int) (ConfigUtility.scrWidth * 0.7);
		    layoutPlayer.getLayoutParams().width = ConfigUtility.scrWidth;
		    layoutPlayer.getLayoutParams().height = (int) (ConfigUtility.scrWidth * 0.8);
		}
		setVideoLayout();
	};
	
	private void setVideoLayout() {
		if (mVideoView != null)
			mVideoView.setVideoLayout(mVideoMode, 0);
	}
	
	@Override
	public void onCompletion(MediaPlayer paramMediaPlayer) {
//		Toast.makeText(mainActivity, "done", 0).show();
		needResume = true;
		if (mProgress != null) {
			Log.d("Video", "completed");
			mProgress.setProgress(0);
			updatePausePlay();
		}
	}

	public boolean onTouchThis(MotionEvent event) {
		Log.e("VideoPlayerFragment", "onTouch");
		try {
			if (mGestureDetector.onTouchEvent(event))
				return true;
	
			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_UP:
				endGesture();
				if (isShowing == true) {
					mHandleController.sendEmptyMessage(FADE_OUT);
				}
				else 
					mHandleController.sendEmptyMessage(SHOW_PROGRESS);
				break;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	public void onDestroyView() {
		try {
			((MainActivity) getActivity()).mainFragment.showHeader(true);
		} catch (Exception e) {
		}
		super.onDestroyView();
	}
	
	private class TagOnClickListener implements OnClickListener {

		private String tag;
		public TagOnClickListener(String tag) {
			this.tag = tag;
		}
		
		@Override
		public void onClick(View v) {
			doPauseResume();
			((MainActivity) getActivity()).openSearchFragmen(tag, Constants.TAB_VIEW_SEARCH_VIDEO, true);
		}
	}
	
	public void requestVideoSuggestion() {

		adapterVideosSuggestion.setAvatarImageSize();
		adapterVideosSuggestion.resetList();
		
	}
	
	public void requestVideoComments() {

		adapterVideoComments.resetList();
	}
	
	public void switchMenuVideo(int tabId) {
		
		switch (tabId) {
		case TAB_INTRODUCTION:
			// Menu color
			buttonIntroduction.setBackgroundResource(R.drawable.bg_red_normal);
			buttonSuggestion.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			buttonComments.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			
			// Layout content
			layoutIntroduction.setVisibility(View.VISIBLE);
			layoutSuggestion.setVisibility(View.GONE);
			layoutComments.setVisibility(View.GONE);
			break;
			
		case TAB_SUGGESTION:
			// Menu color
			buttonIntroduction.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			buttonSuggestion.setBackgroundResource(R.drawable.bg_red_normal);
			buttonComments.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			
			// Layout content
			layoutIntroduction.setVisibility(View.GONE);
			layoutSuggestion.setVisibility(View.VISIBLE);
			layoutComments.setVisibility(View.GONE);
			
			// Request data (if needed)
			requestVideoSuggestion();
			break;
			
		case TAB_COMMENTS:
			// Menu color
			buttonIntroduction.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			buttonSuggestion.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			buttonComments.setBackgroundResource(R.drawable.bg_red_normal);
			
			// Layout content
			layoutIntroduction.setVisibility(View.GONE);
			layoutSuggestion.setVisibility(View.GONE);
			layoutComments.setVisibility(View.VISIBLE);
			
			// Request data (if needed)
			requestVideoComments();
			break;
			
		default:
			break;
		}
		
//		setPaddingAllButton();
		
	}
	
	private void setPaddingAllButton() {
		int paddingDP = (int)(10 * ConfigUtility.scale);
		buttonIntroduction.setPadding(paddingDP, paddingDP, paddingDP, paddingDP);
		buttonSuggestion.setPadding(paddingDP, paddingDP, paddingDP, paddingDP);
		buttonComments.setPadding(paddingDP, paddingDP, paddingDP, paddingDP);
	}
	
	@Override
	public void onClick(View v) {
		if (v == buttonIntroduction) {
			switchMenuVideo(TAB_INTRODUCTION);
		} else if (v == buttonSuggestion) {
			switchMenuVideo(TAB_SUGGESTION);
		} else if (v == buttonComments) {
			switchMenuVideo(TAB_COMMENTS);
		} else if (v == buttonComment) {
			postComment();
		}
	}
	
	public void postComment() {
		String comment = edtComment.getText().toString();
		if (comment != null && comment.length() > 0) {
			mainActivity.postComment(Constants.COMMENT_TYPE_VIDEO, videoId, comment, new ResponseListener() {
				
				@Override
				public void processResponse(int inintstall) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void processResponse(String response) {
					 boolean resultPostComment = ParseJSON.getResultPostCommentFromResponse(response);
					 if (resultPostComment) {
						 edtComment.setText("");
//						 isRequestCommentData = false;
						 requestVideoComments();
					 }
				}
			});
		} else {
			DialogUtility.showDialogAlert(mainActivity, null, getString(R.string.text_empty_comment), getString(R.string.label_close),
				new DialogListener() {
					public void after() {
						showKeyBoard(edtComment);
					}
				});
		}
		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
			      Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edtComment.getWindowToken(), 0);
	}
	public void showKeyBoard(EditText editText) {
		if (editText != null) {
			editText.setFocusable(true);
			editText.setFocusableInTouchMode(true);
			editText.requestFocus();
			InputMethodManager inputMethodManager = ((InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE));
			inputMethodManager.showSoftInput(editText, 1);
		}
	}
	// ========= Media Controller =================================================
	private void showMediaController(boolean isShow) {
		Log.e("VIDEO", "showMediaController");
		if (isShow) {
			layoutController.setVisibility(View.VISIBLE);
			isShowing = true;
		} else {
			layoutController.setVisibility(View.GONE);
			isShowing = false;
		}
	}
	
	private Handler mHandleController = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FADE_OUT:
				showMediaController(false);
				mHandleController.removeMessages(SHOW_PROGRESS);
				break;
			case SHOW_PROGRESS:
				showMediaController(true);
				mHandleController.removeMessages(FADE_OUT);
				if (isShowing) {
					mHandleController.sendEmptyMessageDelayed(FADE_OUT, sDefaultTimeout);
				}
				break;
			default:
				break;
			}
		};
	};
	
	private Handler mHandleTime = new Handler();
	private Runnable mRunnable = new Runnable() {
		
		@Override
		public void run() {
			if (isShowing == true) {
				setProgress();
			}
			mHandleTime.postDelayed(mRunnable, 1000);
		}
	};
	
	private long setProgress() {
		if (mVideoView == null)
			return 0;

		long position = mVideoView.getCurrentPosition();
		long duration = mVideoView.getDuration();
		if (mProgress != null && mVideoView.isPlaying()) {
			if (duration > 0) {
				long pos = 1000L * position / duration;
				mProgress.setProgress((int) pos);
			}
			int percent = mVideoView.getBufferPercentage();
			mProgress.setSecondaryProgress(percent * 10);
		}

		mDuration = duration;

		if (mEndTime != null)
			mEndTime.setText(StringUtils.generateTime(mDuration));
		if (mCurrentTime != null)
			mCurrentTime.setText(StringUtils.generateTime(position));

		return position;
	}
	
	private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
		//@Override
	    public void onStartTrackingTouch(SeekBar bar) {
			mDragging = true;
//			show(3600000);
//			mHandler.removeMessages(SHOW_PROGRESS);
			if (mInstantSeeking)
				mAM.setStreamMute(AudioManager.STREAM_MUSIC, true);
//			if (mInfoView != null) {
//				mInfoView.setText("");
//				mInfoView.setVisibility(View.VISIBLE);
//			}
		}
	
		//@Override
	    public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
			if (!fromuser)
				return;

			long newposition = (mDuration * progress) / 1000;
			String time = StringUtils.generateTime(newposition);
			if (mInstantSeeking)
				mVideoView.seekTo(newposition);
//			if (mInfoView != null)
//				mInfoView.setText(time);
			if (mCurrentTime != null)
				mCurrentTime.setText(time);
		}
	
		//@Override
	    public void onStopTrackingTouch(SeekBar bar) {
			if (!mInstantSeeking)
				mVideoView.seekTo((mDuration * bar.getProgress()) / 1000);
//			if (mInfoView != null) {
//				mInfoView.setText("");
//				mInfoView.setVisibility(View.GONE);
//			}
//			show(sDefaultTimeout);
//			mHandler.removeMessages(SHOW_PROGRESS);
			mAM.setStreamMute(AudioManager.STREAM_MUSIC, false);
			mDragging = false;
//			mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
		}
	};
	
	public boolean isPause;
	private View.OnClickListener mPauseListener = new View.OnClickListener() {
		//@Override
		public void onClick(View v) {
			Log.e("MediaController - mPauseListener", "CLICKED play/pause");
			doPauseResume();
		}
	};
	
	private void updatePausePlay() {
		if (mPauseButton == null)
			return;
		if (mVideoView.isPlaying())
			mPauseButton.setImageResource(R.drawable.mediacontroller_pause_button);
		else
			mPauseButton.setImageResource(R.drawable.mediacontroller_play_button);
	}

	private boolean needResume = false;
	private void doPauseResume() {
		
		if (mVideoView.isPlaying()){
			mVideoView.pause();
			mPauseButton.setImageResource(R.drawable.mediacontroller_play_button);
		}
		else {
			if (needResume) {
				mPauseButton.setImageResource(R.drawable.mediacontroller_pause_button);
				startPlayVideo();
				needResume = false;
			} else {
				mVideoView.start();
				mPauseButton.setImageResource(R.drawable.mediacontroller_pause_button);
			}
			
		}
	}
	
	// ========= Check Vitamio Libs =================================================
	private void checkVitamioLibs() {
		if (!Vitamio.isInitialized(mainActivity)) {
			extractVitamioLibs();
			
		} else {
			startPlayVideo();
		}
//			return;
//			startPlayVideo();
			
		
	}
	
	private void extractVitamioLibs() {
		AsyncTask<String, String, String> asynExtract = new AsyncTask<String, String, String>() {

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				showProgressDialog();
			}
			@Override
			protected String doInBackground(String... params) {
				Vitamio.initialize(mainActivity);
				return null;
			}
			
			@Override
			protected void onPostExecute(String result) {
//				checkVitamioLibs();
				super.onPostExecute(result);
				closeProgressDialog();
				startPlayVideo();
			}
			
		};
		
		asynExtract.execute("");
		
	}
	
	// ========= End Check Vitamio Libs =================================================
	
	private ProgressDialog progressDialog;
	
	// Show/hide Progress Dialog
	public void showProgressDialog() {
		if (progressDialog == null) {
			progressDialog = ProgressDialog.show(mainActivity, null, getResources().getString(R.string.text_processing), true);
			progressDialog.setCancelable(false);
		}
	}

	public void closeProgressDialog() {
		if (progressDialog != null) {
			try {
				progressDialog.cancel();
			} catch (Exception e) { }
			progressDialog = null;
		}
	}
	// 18-05-2014 Bugs #298 start.

	private void changeFullScreen() {
		int landscapeMode = getActivity().getRequestedOrientation();
		if (landscapeMode != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//		Log.e("Fullscreen", "landscap");
		} else {
			getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//		Log.e("Fullscreen", "none landscap");
		}
	}
	@Override
	public boolean onKeyDown(KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			int landscapeMode = getActivity().getRequestedOrientation();
			if (landscapeMode == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//			Log.e("Fullscreen", "landscap");
				return true;
			} else {
				return super.onKeyDown(event);
			}
		} else {
			return super.onKeyDown(event);
		}
	}
	// 18-05-2014 End.
}
